package cn.virens.common.project.base.auth;

import cn.virens.common.util.exception.APIException;
import org.dromara.hutool.core.text.StrUtil;
import org.dromara.hutool.core.text.split.SplitUtil;

import java.util.ArrayList;
import java.util.List;

public class TenantUtil {
    public static final String DOT0 = ":";
    public static final String DOT1 = "@";

    /**
     * 初始化租户权限模式下的关键词字段生成
     *
     * @param model 实体对象
     */
    public static <T extends TenantChildModel> T initialize(T model) throws APIException {
        model.setIdentity(model.getTenantId() + DOT1 + getKey(model));

        return model;
    }

    /**
     * 根据当前内容或者对应的层级列表(租户层级)
     *
     * @param model
     */
    public static <T extends TenantBaseModel> List<String> getLayer1(T model) {
        List<String> answer = new ArrayList<>();

        String temp = "";
        for (String item : getTenantArr(model)) {
            answer.add(temp += item);

            temp += DOT0;
        }

        return answer;
    }

    /**
     * 根据当前内容或者对应的层级列表
     *
     * @param model
     */
    public static <T extends TenantBaseModel> List<String> getLayer0(T model) {
        List<String> answer = new ArrayList<>();
        String temp = getTenant(model) + DOT1;

        for (String item : getKeyArr(model)) {
            answer.add(temp += item);

            temp += DOT0;
        }

        return answer;
    }

    /**
     * 获取租户部分(按层级分割)
     */
    public static <T extends TenantBaseModel> List<String> getTenantArr(T model) {
        return SplitUtil.split(getTenant(model), DOT0);
    }

    /**
     * 获取业务部分(按层级分割)
     */
    public static <T extends TenantBaseModel> List<String> getKeyArr(T model) {
        return SplitUtil.split(getKey(model), DOT0);
    }

    /**
     * 获取租户部分
     */
    public static <T extends TenantBaseModel> String getTenant(T model) {
        return getTenant(model.getIdentity());
    }

    /**
     * 获取租户部分
     */
    public static String getTenant(String identity) {
        return StrUtil.subBefore(identity, DOT1, true);
    }

    /**
     * 获取业务部分
     */
    public static <T extends TenantBaseModel> String getKey(T model) {
        return getKey(model.getIdentity());
    }

    /**
     * 获取业务部分
     */
    public static String getKey(String identity) {
        return StrUtil.subAfter(identity, DOT1, true);
    }
}
